import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_video.dart';
import 'package:flutter_learn_vi/src/page/study/course/video_details_screen_full_widget.dart';
import 'package:flutter_learn_vi/src/page/study/course/video_progress_request_model.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

import '../../../bean/bean_global.dart';
import '../../../bean/bean_integral.dart';
import '../../../bean/bean_train.dart';
import '../../../bean/bean_user_account.dart';
import '../../../bean/bean_video_course.dart';
import '../../../common/global.dart';
import '../../../common/user_helper.dart';
import '../../../face/face_detector_view.dart';
import '../../../net/dio_utils.dart';
import '../../../utils/toast_utils.dart';
import '../cache/CustomCacheManager.dart';
import '../controller/course_video_details_controller.dart';
import '../controller/video_details_local_controller.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/18.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class VideoDetailsWidget extends StatefulWidget {
  final bool isFullScreen;
  final bool isShowBack;
  final VideoModel init;

  ///积分配置
  final IntegralStatBean integralStatBean;

  //任务配置
  final TaskBean taskBean;

  ///培训入口进入
  final int trainId;
  final TrainBean trainBean;

  //当前的播放进度
  final Duration currentDuration;

  VideoDetailsWidget(
      {Key key,
      this.trainId,
      this.trainBean,
      this.integralStatBean,
      this.taskBean,
      this.isFullScreen = false,
      this.isShowBack = false,
      this.currentDuration,
      this.init})
      : super(key: key);

  @override
  _VideoDetailsWidgetState createState() => _VideoDetailsWidgetState();
}

class _VideoDetailsWidgetState extends State<VideoDetailsWidget>
    with VideoProgressRequestModel {
  //创建视频播放控制器
  VideoPlayerController _controller;
  bool _isPlay = false;
  bool _isLoading = true;
  VideoDetailsLocalController _videoDetailsLocalController;

  @override
  void initState() {
    super.initState();
    _videoDetailsLocalController = Get.put(
        VideoDetailsLocalController(widget.init.id),
        tag: "${widget.init.id}");
    _videoDetailsLocalController.isClose = false;
    _rankStatBean = widget.integralStatBean;
    _taskBean = widget.taskBean;
    LogUtils.e("播放视频  ${widget.init.videoUrl}");

    ///人脸识别计时
    faceRecognitionNumber = UserHelper.getInstance.faceRecognitionNumber;
    initController(widget.init.videoUrl);
  }

  @override
  void dispose() {
    stopVideo(dispose: true);
    _streamController.close();
    if (_timer != null && _timer.isActive) {
      _timer.cancel();
    }
    if (_playTimer != null && _playTimer.isActive) {
      _playTimer.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        //第一层的视频
        Positioned.fill(
          child: GestureDetector(
            onTap: () {
              _controller.pause();
              _isPlay = false;
              setState(() {});
            },
            child: (_controller == null || _controller.value == null)
                ? Container()
                : AspectRatio(
                    aspectRatio: _controller.value.aspectRatio,
                    child: VideoPlayer(_controller),
                  ),
          ),
        ),

        //第二层的控制按钮
        buildControllerWidget(),
        buildLoading(),
      ],
    );
  }

  Timer _timer;
  double _opacity = 1.0;
  bool _isFirst = true;

  Widget buildControllerWidget() {
    //动画过渡透明度组件
    return AnimatedOpacity(
      //过渡时间
      duration: Duration(milliseconds: 200),
      opacity: _opacity,
      child: GestureDetector(
        onTap: () {
          setState(() {
            _opacity = 1.0;
          });
          //创建一个延时执行的定时 器
          _timer = Timer(Duration(seconds: 3), () {
            setState(() {
              _opacity = 0.0;
            });
          });
        },
        child: Stack(
          children: [
            //层叠布局中的填充
            Positioned.fill(
              child: Container(
                //底部内边距
                padding: EdgeInsets.only(bottom: 20),
                //0.3 的蓝色透明度
                color: Colors.blueGrey.withOpacity(0.5),
                //手势监听
                child: GestureDetector(
                  //手指抬起后的回调
                  onTap: controllerClickFunction,
                  //层叠布局
                  child: Stack(
                    //子Widget居中对齐
                    alignment: Alignment.center,
                    children: [
                      ClipOval(
                        child: Container(
                          width: 54,
                          height: 54,
                          decoration: BoxDecoration(
                              gradient: RadialGradient(colors: [
                            Colors.black,
                            Colors.black.withOpacity(0.3),
                          ])),
                          child: Icon(
                            _controller == null ||
                                    _controller.value == null ||
                                    _controller.value.isPlaying
                                ? Icons.pause
                                : Icons.play_arrow_sharp,
                            size: 33,
                            color: Colors.white,
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
            //顶部对齐的文本
            buildPositioned(),
            //底部的滑动条
            Positioned(
              bottom: 10,
              left: 10,
              right: 10,
              height: 60,
              child: buildBottomController(),
            )
          ],
        ),
      ),
    );
  }

  Widget buildPositioned() {
    return Positioned(
      top: 10,
      left: 10,
      right: 10,
      height: 44,
      child: Row(
        children: [
          widget.isShowBack
              ? BackButton(
                  color: Colors.white,
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                )
              : Container(),
          Expanded(
            child: Text(
              "",
              style: TextStyle(
                fontWeight: FontWeight.w500,
                color: Colors.white,
                fontSize: 18,
              ),
            ),
          )
        ],
      ),
    );
  }

  ///控制层点击事件
  void controllerClickFunction() async {
    //获取当前视频是否在播放
    bool isPlaying = _controller.value.isPlaying;
    if (isPlaying) {
      //如果视频正在播放中 再次点击停止播放
      stopVideo();
      //停止播放状态下 取消隐藏的计时器
      if (_timer != null && _timer.isActive) {
        _timer.cancel();
      }
      //取消视频更新记录
      if (_playTimer != null && _playTimer.isActive) {
        _playTimer.cancel();
      }
      //执行一次内容更新
      updateVideoProgress();
    } else {
      //开始播放视频
      startPlayVide(true);
      //开始计时
      startPlayTimer();
      //创建一个延时执行的定时器
      _timer = Timer(Duration(seconds: 5), () {
        //3秒后将控制层的透明度设置为0
        //控制层还在
        setState(() {
          _opacity = 0.0;
        });
      });
    }
  }

  ///点击暂停时执行一次
  ///播放完成时 执行一次
  ///15分钟自动暂停 执行一次
  ///页面闭关的时候会 执行一次
  Future<bool> updateVideoProgress({bool finish = false}) async {
    if (_controller.value == null) {
      isFinishUpdateProgress = false;
      return false;
    }
    if (_studyFinish != 0) {
      isFinishUpdateProgress = false;
      return false;
    }

    ///0 学习未完成  1学习完成

    //视频播放的当前时间进度
    Duration currentDuration = _controller.value.position;
    //视频的总时长
    Duration totalDuration = _controller.value.duration;
    if (currentDuration == null || totalDuration == null) {
      isFinishUpdateProgress = false;
      return false;
    }

    _currentTimers2 = currentDuration.inMilliseconds ~/ 1000;
    LogUtils.e("视频进度更新 _currentTimers2 $_currentTimers2");
    if (Get.isRegistered<CourseVideoDetailsController>(
        tag: "${widget.init.videoCourseId}")) {
      CourseVideoDetailsController controller =
          Get.find<CourseVideoDetailsController>(
              tag: "${widget.init.videoCourseId}");
      await controller.clickStopVideo(
        videoId: widget.init.id,
        videoCourseId: widget.init.videoCourseId,
        inMilliseconds: currentDuration.inMilliseconds,
        finish: finish,
      );
      isFinishUpdateProgress = false;
      return true;
    } else {
      LogUtils.e("视频进度更新 更新失败 CourseVideoDetailsController 未注册");
    }
    isFinishUpdateProgress = false;
    return false;
  }

  int _currentTimers2;
  int _studyFinish = 0;

  ///开始播放视频
  void startPlayVide(bool flag) {
    _isPlay = true;
    _isFirst = false;
    //发送消息
    //先暂停再播放

    if (Get.isRegistered<CourseVideoDetailsController>(
        tag: "${widget.init.videoCourseId}")) {
      CourseVideoDetailsController controller =
          Get.find<CourseVideoDetailsController>(
              tag: "${widget.init.videoCourseId}");
      controller.clickPlayVideo(videoId: widget.init.id);
    }

    if (flag) {
      //当前视频 播放的位置
      Duration postion = _controller.value.position;
      //视频的总长度
      Duration duration = _controller.value.duration;

      if (postion == duration) {
        //播放完毕 再点击播放时，当播放位置滑动到开始位置
        _controller.seekTo(Duration.zero);
      }
    }
    if (widget.currentDuration != null &&
        _controller.value != null &&
        _controller.value.duration != null &&
        _controller.value.duration.inMicroseconds > 0) {
      if (widget.currentDuration < _controller.value.duration) {
        _controller.seekTo(widget.currentDuration);
      }
    } else {
      if (_currentTimers2 != null && _currentTimers2 > 0) {
        LogUtils.e("视频进度更新 开始播放 _currentTimers2 $_currentTimers2");
        _controller.seekTo(Duration(seconds: _currentTimers2));
      }
    }
    //开始播放
    _controller.play();

    setState(() {});
  }

  double _currentSlider = 0.0;
  StreamController<int> _streamController = new StreamController();

  buildBottomController() {
    if (_isFirst) {
      return Container();
    }
    //评论区有文章回复支持
    return StreamBuilder(
      stream: _streamController.stream,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        return Row(
          children: [
            Text(
              buildStartText(),
              style: TextStyle(fontSize: 14, color: Colors.white),
            ),
            Expanded(
              child: _studyFinish == 0
                  ? Padding(
                      padding: EdgeInsets.only(
                        left: 10,
                        right: 10,
                      ),
                      child: LinearProgressIndicator(
                        value: _currentSlider,
                      ),
                    )
                  : Slider(
                      //滑动条当前的进度
                      value: _currentSlider,
                      //滑动条滑动时的回调
                      onChanged: (value) {
                        setState(() {
                          _currentSlider = value;
                          //控制视频
                          if (_studyFinish == 1) {
                            Duration duration =
                                _controller.value.duration * value;
                            LogUtils.e("快进 ${duration.inSeconds}");
                            _controller.seekTo(duration);
                          }
                        });
                      },
                      min: 0.0,
                      max: 1.0,
                      //滑动条的底色
                      inactiveColor: Colors.white,
                      //滑动条的进度颜色
                      activeColor: Colors.redAccent,
                    ),
            ),
            Text(
              buildEndText(),
              style: TextStyle(fontSize: 14, color: Colors.white),
            ),
            InkWell(
              onTap: () {
                if (widget.isFullScreen) {
                  Navigator.of(context).pop(_controller.value.position);
                } else {
                  _controller.pause();
                  IntegralStatBean themStatBean;
                  if (_isRecoder) {
                    _isRecoder = false;
                    themStatBean = _rankStatBean;
                  }
                  TaskBean themTaskBean;
                  if (_isTaskBean) {
                    _isTaskBean = false;
                    themTaskBean = _taskBean;
                  }
                  NavigatorUtils.openPageByFade(
                      context,
                      VideoDetailsScreenFullWidget(
                        isFullScreen: true,
                        integralStatBean: themStatBean,
                        taskBean: themTaskBean,
                        currentDuration: _controller.value.position,
                        init: widget.init,
                        trainId: widget.trainId,
                        trainBean: widget.trainBean,
                      ), dismissCallBack: (value) {
                    if (value != null) {
                      Duration currehtDuration = value;
                      _controller.seekTo(currehtDuration);
                      _controller.play();
                    }
                  });
                }
              },
              child: Container(
                padding: EdgeInsets.only(left: 10, right: 2),
                child: Image.asset(
                  widget.isFullScreen
                      ? "assets/images/2.0x/video_mini.png"
                      : "assets/images/2.0x/video_full.png",
                  width: 22,
                ),
              ),
            )
          ],
        );
      },
    );
  }

  //获取时实播放的时间
  String buildStartText() {
    //视频当前的播放进度
    Duration duration = _controller.value.position;
    if (duration == null) {
      return "";
    }
    int m = duration.inMinutes;
    int s = duration.inSeconds;
    List<String> parts = duration.toString().split(':');
    if (parts.length < 3) {
      return "--:--";
    }
    if (parts[1] == "0") {
      return '${parts[2].split(".")[0]}秒';
    }
    if (parts[0] == "0") {
      return '${parts[1]}:${parts[2].split(".")[0]}';
    }
    return '${parts[0]}:${parts[1]}:${parts[2].split(".")[0]}';
  }

  String buildEndText() {
    //视频总的时长
    Duration duration = _controller.value.duration;
    if (duration == null) {
      return "";
    }

    List<String> parts = duration.toString().split(':');
    if (parts.length < 3) {
      return "--:--";
    }
    if (parts[1] == "0") {
      return '${parts[2].split(".")[0]}秒';
    }
    if (parts[0] == "0") {
      return '${parts[1]}:${parts[2].split(".")[0]}';
    }
    return '${parts[0]}:${parts[1]}:${parts[2].split(".")[0]}';
  }

  ///停止播放视频
  Future<bool> stopVideo({bool dispose = false}) async {
    if (_controller != null && _controller.value != null) {
      if (_controller.value.isPlaying) {
        //视频播放控制器停止播放
        await _controller.pause();
        if (dispose) {
          await _controller.dispose();
          _controller = null;
        }
      }
    }
    //变量标识
    _isPlay = false;
    if (!dispose) {
      if (mounted) {
        setState(() {});
      }
    }
    return true;
  }

  void initController(String videoUrl) async {
    if (_controller != null) {
      //await stopVideo();
    }
    LogUtils.e("开始获取用户学习视频的详情 ${widget.init.id}");

    if (Get.isRegistered<CourseVideoDetailsController>(
        tag: "${widget.init.videoCourseId}")) {
      CourseVideoDetailsController controller =
          Get.find<CourseVideoDetailsController>(
              tag: "${widget.init.videoCourseId}");

      UserStudyCourseBean userStudyCourseBean =
          await controller.getcCurrentVideoProgress(videoId: widget.init.id);
      if (userStudyCourseBean != null) {
        ///0 学习未完成  1学习完成
        _studyFinish = userStudyCourseBean.studyFinish;
        if (_studyFinish == 0) {
          _currentTimers2 = userStudyCourseBean.studySecond;
          LogUtils.e("学习未完成 当前进度 _currentTimers2 $_currentTimers2");
        } else {
          LogUtils.e("学习已完成 可以自由查看");
        }
      }
    }
    LogUtils.e("开始播放 $videoUrl");
    File file =
        await CustomCacheManager.getCacheVideo(key: "${widget.init.id}");
    VideoPlayerController controller;
    if (file != null) {
      controller = VideoPlayerController.file(file);
    } else {
      Map<String, String> map = {"url": videoUrl, "key": "${widget.init.id}"};
      rootStreamController.add(GlobalBean(205, map));
      // CustomCacheManager.cacheVideo(url: videoUrl, key: "${widget.init!.id}");
      controller = VideoPlayerController.network(videoUrl);
    }
    final old = _controller;
    if (old != null) {
      old.removeListener(videoListener);
      old.pause(); // mute instantly
    }
    _controller = controller;
    controller.initialize().then((_) {
      LogUtils.e("加载完成");
      // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
      Future.delayed(Duration.zero, () {
        _isLoading = false;
        setState(() {});
      });
      startSetting();
    });

    //视频播放的实时更新
    _controller.addListener(videoListener);
    _videoDetailsLocalController.initVideoController(_controller);
  }

  IntegralStatBean _rankStatBean;
  bool _isRecoder = true;

  TaskBean _taskBean;
  bool _isTaskBean = true;

  void videoListener() async {
    if (_videoDetailsLocalController.isClose) {
      LogUtils.e("页面闭关 不执行 videoListener 中的方法");
      return;
    }
    if (_isPlay && !_controller.value.isPlaying) {
      _isPlay = false;
      if (mounted) {
        setState(() {});
      }
    }

    //视频播放的当前时间进度
    Duration currentDuration = _controller.value.position;
    //视频的总时长
    Duration totalDuration = _controller.value.duration;

    if (currentDuration != null && totalDuration != null) {
      _videoDetailsLocalController.updateProgress(
        currentDuration,
        totalDuration,
        widget.init.videoCourseId,
      );
      //滑动条进度
      if (_opacity == 1.0) {
        _streamController.add(0);
      }
      if (currentDuration.compareTo(totalDuration) == 0) {
        LogUtils.e("播放完成");
        playFinishFunction();
      }
    }
  }

  void startSetting() {
    _controller.addListener(videoListener);
    if (widget.isFullScreen) {
      startPlayVide(false);
    }
  }

  bool isFinishUpdateProgress = false;

  void playFinishFunction() async {
    LogUtils.e("视频播放完成 更新视频进度 "
        "progress:${isFinishUpdateProgress}  value:${_controller.value}");
    if (!isFinishUpdateProgress && _controller.value != null) {
      isFinishUpdateProgress = true;
      Duration totalDuration = _controller.value.duration;
      LogUtils.e("视频播放完成 更新视频进度 ${totalDuration.inSeconds}");
      updateVideoProgress(finish: true);
    }
  }

  ///10执行一次的定时器
  Timer _playTimer;

  ///自动暂停计时
  int autoStopNumber = 0;

  ///人脸识别计时
  int faceRecognitionNumber = 0;

  void startPlayTimer() {
    if (_playTimer != null) {
      _playTimer.cancel();
      _playTimer = null;
    }
    _playTimer = Timer.periodic(Duration(seconds: 1), (timer) async {
      autoStopNumber += 1;
      faceRecognitionNumber += 1;
      UserHelper.getInstance.faceRecognitionNumber = faceRecognitionNumber;

      if (_isPlay && _controller.value != null) {
        if (_taskBean != null && _isTaskBean) {
          _isTaskBean = false;
          requestTaskRecoder(
              itemId: widget.init.id,
              taskId: _taskBean.id,
              title: widget.init.videoName);
        }

        //视频播放的当前时间进度
        Duration currentDuration = _controller.value.position;
        //视频的总时长
        Duration totalDuration = _controller.value.duration;

        LogUtils.e("计时 $autoStopNumber 当前播放的时长 ${currentDuration.inSeconds} 秒");
        if (autoStopNumber % 120 == 0) {
          LogUtils.e("2分钟自动更新进度 ${currentDuration.inSeconds}");
          if (currentDuration != null && totalDuration != null) {
            updateVideoProgress();
          }
        }

        bool isShowFaceCheck = UserHelper.getInstance.isShowFaceCheck();
        if (!isShowFaceCheck) {
          debugPrint("人脸识别权限未打开");
          return;
        }

        ///-----------------视频 培训人脸识别信息判断 ---------------------------------------------------------start ----------------------------------------------------------
        if (widget.trainBean != null) {
          String faceRecognition = widget.trainBean.faceRecognition;
          if (faceRecognition == "on") {
            //自动识别的间隔时间 分钟
            int faceRecognitionTime = widget.trainBean.faceRecognitionTime;
            //分钟转秒
            int faceRecognitionTimeSeconds = faceRecognitionTime * 60;
            //测试使用
            //faceRecognitionTimeSeconds = 10;
            //如果本地时间大于人脸识别时间
            debugPrint(
              "人脸识别时间 faceRecognitionTimeSeconds：$faceRecognitionTimeSeconds  faceRecognitionNumber：${faceRecognitionNumber}",
            );

            if (faceRecognitionNumber > faceRecognitionTimeSeconds) {
              debugPrint("需要开启人脸识别 暂停播放");
              updateVideoProgress();
              LogUtils.e("定时器 统计用户学习记录详情 ---人脸识别时间上报播放记录");
              _controller.pause();
              _isPlay = false;
              _opacity = 1.0;
              setState(() {});
              dynamic result = await Get.defaultDialog(
                  title: "提示",
                  content: Text("本培训需要人脸识别认证"),
                  textCancel: "取消",
                  textConfirm: "去认证",
                  radius: 10,
                  onConfirm: () {
                    Get.back(result: true);
                  });
              if (result == null || !result) {
                debugPrint("未选择去认证");
                ToastUtils.showToast("需要认证后才能继续学习");
                return;
              }

              dynamic faceResult = await Get.to(() => FaceDetectorView(
                    key: UniqueKey(),
                  ));
              if (faceResult == null || faceResult.toString().isEmpty) {
                ToastUtils.showToast("需要认证后才能继续学习");
                return;
              }
              //比对一下当前的人脸数据
              ResponseInfo statisRresponseInfo = await DioUtils.instance
                  .postRequest(
                      url: HttpHelper.compareFaceUrl,
                      encrypt: false,
                      jsonMap: {
                    "videoId": widget.init.id,
                    "trainId": widget.trainId,
                    "faceType": "train",
                    "faceImageUrl": faceResult.toString(),
                  });

              if (statisRresponseInfo.success) {
                //识别成功 继续播放
                debugPrint("人脸识别成功 继续播放");
                faceRecognitionNumber = 0;
                _controller.play();
                _isPlay = true;
                _opacity = 0.0;
                setState(() {});
              } else {
                Get.defaultDialog(
                    radius: 10,
                    title: "人脸信息核定失败",
                    content: Text(statisRresponseInfo.message ?? "网络请求错误"),
                    textCancel: "关闭");
                return;
              }
            }
          }
        }

        ///-----------------视频 培训人脸识别信息判断 ---------------------------------------------------------end ----------------------------------------------------------

        //15分钟自动暂停 //去除
        // if (autoStopNumber % 900 == 0) {
        //   LogUtils.e("15分钟自动暂停 ${currentDuration.inSeconds}");
        //   _controller.pause();
        //   _isPlay = false;
        //   _opacity = 1.0;
        //   setState(() {});
        //
        //   ///------------------------------------------------------------
        //   if (currentDuration != null && totalDuration != null) {
        //     LogUtils.e("更新视频进度 ${currentDuration.inSeconds}");
        //     updateVideoProgress();
        //   } else {
        //     if (currentDuration == null) {
        //       LogUtils.e("更新视频进度 失败 currentDuration is null");
        //     }
        //     if (totalDuration == null) {
        //       LogUtils.e("更新视频进度 失败 totalDuration is null");
        //     }
        //   }
        // }
        if (currentDuration != null && totalDuration != null) {
          _currentSlider =
              currentDuration.inMilliseconds / totalDuration.inMilliseconds;
          _streamController.add(0);
          LogUtils.e("_currentSlider is  $_currentSlider");
        }

        ///------------------------------------------------------------
        if (_rankStatBean != null && _isRecoder) {
          if (_rankStatBean.readTimes < totalDuration.inSeconds) {
            if (currentDuration.inSeconds >= _rankStatBean.readTimes) {
              _isRecoder = false;
              requestPlayRecoder(
                  videoId: widget.init.id, configId: _rankStatBean.id);
            }
          }
        }
      }
    });
  }

  buildLoading() {
    if (_isLoading) {
      return Center(
        child: CircularProgressIndicator(),
      );
    }
    return Container();
  }
}
